Troubleshooting pits using @ Value of ${× × × values from properties files
- 2021-10-24 22:53:53
- OfStack
@ Value (${× × ×)) takes value from properties file
Premises:
Your entity class has been added to the IOC container (with annotations such as @ Compenet)
Error reporting code:
@Value("${driver}")
private String driver;
@Value("${url}")
private String url;
@Value("${username}")
private String userName;
@Value("${password}")
private String password;
properties file
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/abc?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
username=root
password=admin
At this time, you can't get the value in properties file by writing @ Value annotation like this
You must prefix the properties file attributes (arbitrary)
Such as:
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/abc?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
jdbc.username=root
jdbc.password=admin
The corresponding class should also be modified
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String userName;
@Value("${jdbc.password}")
private String password;
So you can get it normally
Additional:
1. Static variables cannot be injected
2. The default properties file for Springboot is application. properties
Spring @ Value ("${}") null value processing
Scenario:
The Test class has one property email configured in application. properties
@Value("${email}")
private String email;
If email is not configured in the configuration, when the application starts, it will report that this attribute exception cannot be found, resulting in startup failure.
Solution 1:
Add @ Component and @ Lazy to the Test class at the same time
Solution 2:
The @ ConditionalOnProperty annotation is provided in springboot
Set injection conditions
@ConditionalOnProperty(name = "flag", havingValue = "true")
bean is instantiated only if the flag property in the configuration file application. properties is true